import oss2
import requests
import os


def init_auth():
    # 填写RAM用户的Access Key ID和Access Key Secret
    access_key_id = 'LTAI5t8195wDoXzc7KkCMHar'
    access_key_secret = '8DX5sgVVG6Eg5QQqG09lJV1AH3Y9Nx'

    # 使用RAM用户的访问密钥配置访问凭证，请注意，此处使用AuthV4表示使用V4签名。
    auth = oss2.AuthV4(access_key_id, access_key_secret)

    # 填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
    endpoint = "https://oss-cn-hangzhou.aliyuncs.com"

    # 填写Endpoint对应的Region信息，例如cn-hangzhou。注意，v4签名下，必须填写该参数
    region = "cn-hangzhou"

    # 返回初始化后的auth, endpoint, region
    return auth, endpoint, region


def upload_oss(url, save_path):
    auth, endpoint, region = init_auth()

    # yourBucketName填写存储空间名称。
    bucket = oss2.Bucket(auth, endpoint, "orange-ai-1", region=region)

    # requests.get返回的是一个可迭代对象（Iterable），此时Python SDK会通过Chunked Encoding方式上传。
    # 填写网络流地址。
    input = requests.get(url)
    # 填写Object完整路径。Object完整路径中不能包含Bucket名称。
    bucket.put_object(save_path, input)
    return 'https://orange-ai-1.oss-cn-hangzhou.aliyuncs.com/'+save_path


def upload_local_file_to_oss(local_file_path, save_path):
    """
    将本地文件上传到阿里云OSS
    
    Args:
        local_file_path: 本地文件的完整路径
        save_path: OSS上的保存路径，不包含Bucket名称
        
    Returns:
        str: 上传成功后的文件访问URL
    """
    # 检查本地文件是否存在
    if not os.path.exists(local_file_path):
        raise FileNotFoundError(f"本地文件不存在: {local_file_path}")
    
    auth, endpoint, region = init_auth()
    bucket_name = "orange-ai-1"
    bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)
    
    try:
        # 使用with语句打开文件，确保文件正确关闭
        with open(local_file_path, 'rb') as file_obj:
            # 上传文件到OSS
            result = bucket.put_object(save_path, file_obj)
            
            # 检查上传结果
            if result.status == 200:
                print(f"文件上传成功: {local_file_path} -> {save_path}")
                # 返回文件的访问URL
                return f'https://{bucket_name}.oss-cn-hangzhou.aliyuncs.com/{save_path}'
            else:
                raise Exception(f"上传失败，状态码: {result.status}")
    except Exception as e:
        print(f"上传文件到OSS时出错: {str(e)}")
        raise
    

# 使用示例
# if __name__ == '__main__':
    # 上传网络文件示例
    # url = 'https://example.com/sample.mp4'
    # save_path = 'test/sample.mp4'
    # print(upload_oss(url, save_path))
    
    # 上传本地文件示例
    # local_file = r"F:\python-study\get-video-images\frames\sample.jpg"
    # oss_path = "frames/sample.jpg"
    # print(upload_local_file_to_oss(local_file, oss_path))
